import os
import serial
import sys
import time
import threading

from ..utils.simple_logging import get_hardware_logger

# 获取硬件日志记录器
logger = get_hardware_logger("tec")

# 检查操作系统类型
if os.name == 'nt':  # Windows 系统

    class TecController:
        def __init__(self, port=None, baudrate=57600):
            logger.info("在 Windows 系统上运行 - 跳过串口连接")
            logger.info("模拟 TEC 控制器 - 串口连接已跳过")
            self.connected = False

        def set_temperature(self, temp):
            logger.debug(f"模拟: 设置温度到 {temp}°C")
            return True

        def get_temperature(self):
            logger.debug("模拟: 获取当前温度 - 返回 25.0°C")
            return 25.0

        def close(self):
            logger.debug("模拟: 关闭 TEC 控制器连接")

else:  # Linux 或其他系统
    import serial

    class TecController:

        def __init__(self, port='/dev/ttySC1', baudrate=57600, timeout=1):
            """初始化串口控制器。"""
            logger.info("在 Linux 系统上运行 - 使用实际串口连接")
            self.port = port
            self.baudrate = baudrate
            self.timeout = timeout
            self.ser = None
            self.connected = self.configure_serial()  
            # 定义回信代码及其对应的信息
            self.reply_messages = {
                0: "设定/查询/保存命令未找到子模块名称，或参数名称。",
                1: "设置成功。",
                2: "设定/查询/保存命令未找到参数名称。",
                3: "设定/查询/保存命令被禁止。",
                4: "设定命令参数值超范围。",
                5: "其它或未知错误。",
                6: "命令格式语法错误。",
                7: "通讯命令里有校验错误。",
                8: "保存正确执行。"
            }
            time.sleep(1)
            if self.connected:
                self.tesw_on()
            else:
               logger.error("无法连接到串口，请检查连接。")

        # 配置并打开串口
        def configure_serial(self):
            """配置串口"""
            try:
                self.ser = serial.Serial(
                    port=self.port,
                    baudrate=self.baudrate,
                    parity=serial.PARITY_NONE,
                    stopbits=serial.STOPBITS_ONE,
                    bytesize=serial.EIGHTBITS,
                    timeout=self.timeout
                )
                logger.info(f"串口已连接：{self.port}")
                return True
            except serial.SerialException as e:
                logger.error(f"串口连接失败: {e}")
                self.ser = None
                return False

        # 收发数据
        def send_and_receive_serial(self, data: str):
            if not self.connected:
                return None
            try:
                self.ser.reset_input_buffer()
                self.ser.write((data + "\r").encode('ascii'))
                response = self.ser.read_until(b'\r').decode('ascii').strip()
                return response
            except Exception as e:
                logger.error(f"串口通信失败: {e}")
                return None
            
        # 查询现在温度
        def get_temperature(self):
            if not self.connected:
                logging.warning("TEC 未连接，返回默认温度 25°C")
                return 25.0
            reply = self.send_and_receive_serial("TC1:TCACTTEMP?")
            if reply and reply.startswith("TC1:TCACTTEMP="):
                return float(reply.split("=")[1])
            return 25.0

        # 设置温度
        def set_temperature(self, temperature: float = 25):
            # 格式化为两位小数
            response = self.send_and_receive_serial(f"TC1:TCADJUSTTEMP={temperature}")
            return response  # 解析设置命令的响应

        # 升温开关
        def tesw_on(self):
            if not self.connected:
                logging.warning("TESW_ON 跳过：TEC 未连接")
                return
            response = self.send_and_receive_serial("TC1:TCSW?")
            if not response:
                logging.warning("TESW_ON 未收到响应")
                return
            if response[-1] == '0':
                self.send_and_receive_serial("TC1:TCSW=1")
                time.sleep(0.5)
                response = self.send_and_receive_serial("TC1:TCSW?")
                if response and response[-1] == '1':
                    logger.info("升温开关已打开")
                else:
                    logger.error("升温开关打开失败")
                    sys.exit("升温开关打开失败")
            else:
                logger.info("升温开关已处于打开状态")

        # 关闭升温开关
        def tesw_off(self):
            # 检查温控开关状态
            response = self.send_and_receive_serial("TC1:TCSW?")
            if response[-1] == '1':
                # 如果温控开关打开，尝试关闭
                self.send_and_receive_serial("TC1:TCSW=0")
                time.sleep(0.5)  # 等待设备响应
                # 再次检查温控开关状态
                response = self.send_and_receive_serial("TC1:TCSW?")
                if response[-1] == '0':
                    logger.info("升温开关关闭成功")
                else:
                    logger.error("升温开关关闭失败")
                    sys.exit("升温开关关闭失败")
            else:
                logger.info("升温开关已处于关闭状态")

        def monitor_temperature(self, target_temp=37.00, tolerance=3.00):
            """设置并监测 TEC 温度"""
            self.set_temperature(target_temp)
            temlist = []
            i = 0
            while self.running:
                i += 1
                if i < 90:
                    tem = self.get_temperature()
                    temlist.append(tem)
                    logger.info(f"当前 TEC 温度: {tem}°C")
                    time.sleep(2)
                else:
                    # 检查温度是否在允许范围内
                    tem = self.get_temperature()
                    if abs(tem - target_temp) > tolerance:
                        temlist.pop(0)
                        temlist.append(tem)
                        logger.error(f"温度异常! 当前温度: {tem}°C, 目标温度: {tem}°C")
                    else:
                        temlist.pop(0)
                        temlist.append(tem)
                    time.sleep(2)  # 每隔 2 秒检查一次

        def start_monitoring(self, temperature=40):
            """启动温度监测"""
            self.running = True
            monitor_thread = threading.Thread(target=self.monitor_temperature, kwargs={"target_temp": temperature})
            monitor_thread.daemon = True  # 设置为守护线程，主线程退出时自动退出
            monitor_thread.start()

        def stop_monitoring(self):
            """停止温度监测"""
            self.running = False
